import json

from django import http
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render

# Create your views here.
from django.views import View
from fdfs_client.client import Fdfs_client
from rest_framework.response import Response

from ihome.utils.response_code import RETCODE
from users.models import User


class UserInfoView(LoginRequiredMixin,View):
    """个人中心"""
    def get(self,request):
        # 获取用户
        # mobile=request.COOKIES.get('mobile')
        user = request.user
        # try:
        #     user=User.objects.get(mobile=mobile)
        # except Exception as ret:
        #     print(ret)
        if not user.is_authenticated:
            return http.JsonResponse({"errno": "4101", "errmsg": "用户未登录"})
        # user = request.user
        if user.avatar is None:
            image_url = ""
        else:
            image_url = user.avatar.url
        data = {
            "avatar_url": image_url,
            "create_time": user.date_joined,
            "mobile": user.mobile,
            "name": user.username,
            "user_id": user.id,
        }
        return http.JsonResponse({"errno":"0", "errmsg":"OK", "data": data})
class UploadView(LoginRequiredMixin,View):
    # 上传头像
    def post(self,request):
        # 接收参数
        avatar = request.FILES.get('avatar')
        # 创建FASTDFS对象
        client = Fdfs_client(settings.FASTDFS_PATH)

        # 4、上传图片
        res = client.upload_by_buffer(avatar.read())
        # 5、判断是否上传成功
        if res['Status'] != 'Upload successed.':
            return http.JsonResponse({'error':"RETCODE.DBERR","errmsg": "图片上传失败"})
        # 获取上传后的路径
        image_url = res["Remote file_id"]

        # # 6、保存图片表
        # user = request.user
        # user.avatar = res['Remote file_id']
        # user.save()
        # data = {
        #     "avatar_url":user
        # }
        # 获取用户id
        user = request.user
        # 保存图片
        user.avatar = image_url
        user.save()
        data = {"avatar_url": user.avatar.url}

        # 7、返回保存后的图片数据
        return http.JsonResponse({"errno":"0","errmsg":"OK","data":data})
class ChangeUserName(LoginRequiredMixin,View):
    # 修改用户名
    def put(self,request):
        # 获取当前用户
        user = request.user
        if user.is_authenticated:
            # 接收参数
            json_dict = json.loads(request.body.decode())
            name = json_dict.get('name')
            try:
                user.username = name
                user.save()
                return http.JsonResponse({"errno":RETCODE.OK,"errmsg":"修改成功",})
            except:
                return http.JsonResponse({"errno":RETCODE.UNKOWNERR,"errmsg":"用户名修改失败"})

        return http.JsonResponse({"errno":"0","errmsg":"未登录",})

class UserAuthentication(View):
    """用户实名认证"""
    def post(self,request):
        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 用户以登录
            # 接受参数
            json_dict = json.loads(request.body.decode())
            real_name = json_dict.get('real_name')
            id_card = json_dict.get('id_card')
            # 校验参数
            # 业务处理
            try:
                # 更新用户名
                user.real_name = real_name
                user.id_card = id_card
                user.save()
                # 返回结果
                return http.JsonResponse({'errno': RETCODE.OK, 'errmsg': '认证信息保存成功'})
            except:
                return http.JsonResponse({'errno': RETCODE.USERERR, 'errmsg': '认证信息保存成功失败'})
        else:
            # 用户未登录
            return http.JsonResponse({'errno': RETCODE.SESSIONERR, 'errmsg': '用户未登录'})

    def get(self, request):
        # 接受参数
        user = request.user
        # 实现逻辑
        data = {
            "real_name": user.real_name,
            "id_card": user.id_card,
        }
        # 返回信息
        return http.JsonResponse({"errno": RETCODE.OK, "errmsg": "认证信息保存成功", "data": data})

